<template>
  <section>
    <div class="columns">
      <div class="column is-full">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span><i class="fa fa fa-book">  更新主题</i></span>
          </div>
          <div>
            <el-form :model="topic" ref="topic" class="demo-topic">
              <el-form-item prop="title">
                <el-input
                  v-model="topic.title"
                  placeholder="输入新的主题名称"
                ></el-input>
              </el-form-item>

              <!--Markdown-->
              <div id="div1"></div>

              <b-taginput
                v-model="tags"
                class="my-3"
                maxlength="15"
                maxtags="3"
                ellipsis
                placeholder="请输入主题标签，限制为 15 个字符和 3 个标签"
              />
              <el-form-item class="mt-3">
                <el-button type="primary" @click="handleUpdate()"
                  >更新
                </el-button>
                <el-button @click="resetForm('topic')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </div>
  </section>
</template>

<script>
import { getTopic, update } from '@/api/post'
import E from 'wangeditor'
let editor

export default {
  name: 'TopicEdit',
  components: {},
  data () {
    return {
      topic: {},
      tags: []
    }
  },
  created () {
    this.fetchTopic()
  },
  methods: {
    renderMarkdown (md) {
      editor = new E('#div1')
      // 配置上传本地图片接口地址
      editor.config.uploadImgServer =
            'http://localhost:2001/files/editor/upload'
      editor.config.uploadFileName = 'file' // 设置上传参数名称
      editor.create()

      editor.txt.html(md)
    },
    fetchTopic () {
      getTopic(this.$route.params.id).then((value) => {
        this.topic = value.data.topic
        this.tags = value.data.tags.map(tag => tag.name)
        this.renderMarkdown(this.topic.content)
      })
    },
    handleUpdate: function () {
      this.topic.content = editor.txt.html()
      update(this.topic).then((response) => {
        const { data } = response
        console.log(data)
        setTimeout(() => {
          this.$router.push({
            name: 'post-detail',
            params: { id: data.id }
          })
        }, 800)
      })
    },

    resetForm (formName) {
      this.$refs[formName].resetFields()
      editor.txt.html('')
      this.tags = ''
    }
  }
}
</script>

<style>
.vditor-reset pre > code {
  font-size: 100%;
}
</style>
